package main

import (
	"database/sql"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	_ "github.com/mattn/go-sqlite3"
)

type Page struct {
	ID      int
	Title   string
	Content string
}

func main() {
	// 初始化Fyne应用
	a := app.New()
	w := a.NewWindow("Notion-like App")
	w.Resize(fyne.NewSize(800, 600))

	// 初始化SQLite
	db, err := sql.Open("sqlite3", "./notes.db")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	_, err = db.Exec("CREATE TABLE IF NOT EXISTS pages (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT)")
	if err != nil {
		panic(err)
	}

	// 页面列表
	pageList := widget.NewList(
		func() int {
			rows, err := db.Query("SELECT COUNT(*) FROM pages")
			if err != nil {
				return 0
			}
			defer rows.Close()
			var count int
			rows.Next()
			rows.Scan(&count)
			return count
		},
		func() fyne.CanvasObject {
			return widget.NewLabel("Page")
		},
		func(id widget.ListItemID, item fyne.CanvasObject) {
			rows, err := db.Query("SELECT id, title FROM pages ORDER BY id LIMIT 1 OFFSET ?", id)
			if err != nil {
				return
			}
			defer rows.Close()
			if rows.Next() {
				var pageID int
				var title string
				rows.Scan(&pageID, &title)
				item.(*widget.Label).SetText(title)
			}
		},
	)

	// 富文本编辑器
	content := widget.NewRichTextFromMarkdown("")
	content.Wrapping = fyne.TextWrapWord

	// 工具栏
	saveButton := widget.NewButton("Save", func() {
		title := "New Page" // 后续可以加标题输入框
		_, err := db.Exec("INSERT INTO pages (title, content) VALUES (?, ?)", title, content.String())
		if err != nil {
			fyne.CurrentApp().SendNotification(fyne.NewNotification("Error", err.Error()))
			return
		}
		fyne.CurrentApp().SendNotification(fyne.NewNotification("Success", "Page saved!"))
		pageList.Refresh()
	})
	boldButton := widget.NewButton("Bold", func() {
		content.Segments = append(content.Segments, &widget.TextSegment{
			Style: widget.RichTextStyle{TextStyle: fyne.TextStyle{Bold: true}},
			Text:  content.String(),
		})
		content.Refresh()
	})

	toolbar := container.NewHBox(saveButton, boldButton)

	// 主内容区
	mainContent := container.NewVBox(toolbar, content)

	// 布局：侧边栏+主内容
	split := container.NewHSplit(pageList, mainContent)
	split.SetOffset(0.2) // 侧边栏占20%宽度

	w.SetContent(split)
	w.ShowAndRun()
}